#include "../heads/LinkList.h"
#include <stdio.h>
#include <stdlib.h>

LinkList createLinkedList() {
    LinkList list;
    list.size = 0;
    list.head = (ListNode *)malloc(sizeof(ListNode)); // 创建哨兵头结点
    if (list.head == NULL) {
        fprintf(stderr, "链表初始化失败：无法为链表分配内存！\n");
        exit(EXIT_FAILURE);
    }
    list.head->next = NULL;
    list.tail = list.head; // 初始化时，尾结点就是头结点
    return list;
}

void addToListHead(LinkList *list, int data) {
    ListNode *newNode = (ListNode *)malloc(sizeof(ListNode));
    if (newNode == NULL) {
        fprintf(stderr, "添加元素失败，无法为链表分配内存！\n");
        exit(EXIT_FAILURE);
    }
    newNode->data = data;
    newNode->next = list->head->next; // 新结点指向原来的第一个数据结点
    list->head->next = newNode; // 头结点指向新结点
    if (list->size == 0) {
        list->tail = newNode; // 如果是第一个元素，更新尾结点
    }
    list->size++;
}

void addToListTail(LinkList *list, int data) {
    ListNode *newNode = (ListNode *)malloc(sizeof(ListNode));
    if (newNode == NULL) {
        fprintf(stderr, "添加元素失败，无法为链表分配内存！\n");
        exit(EXIT_FAILURE);
    }
    newNode->data = data;
    newNode->next = NULL;
    list->tail->next = newNode; // 尾结点指向新结点
    list->tail = newNode; // 更新尾结点
    if (list->size == 0) {
        list->head->next = newNode; // 如果是第一个元素，更新头结点的下一个指针
    }
    list->size++;
}

void removeFromList(LinkList *list, int data) {
    if (list->size == 0) return; // 空链表直接返回

    ListNode *current = list->head;
    while (current->next != NULL && current->next->data != data) {
        current = current->next;
    }
    if (current->next != NULL) {
        ListNode *temp = current->next;
        current->next = temp->next;
        if (temp == list->tail) {
            list->tail = current; // 如果移除的是尾结点，更新尾结点
        }
        free(temp);
        list->size--;
    }
}

ListNode* findInList(LinkList *list, int data) {
    ListNode *current = list->head->next;
    while (current != NULL) {
        if (current->data == data) {
            return current;
        }
        current = current->next;
    }
    return NULL;
}

void printList(LinkList *list) {
    ListNode *current = list->head->next;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

void destroyList(LinkList *list) {
    ListNode *current = list->head;
    while (current != NULL) {
        ListNode *temp = current;
        current = current->next;
        free(temp);
    }
    list->size = 0;
    list->head = NULL;
    list->tail = NULL;
}
